<?php
namespace app\api\controller\v1;

use think\Controller;
use think\Request;
use think\Db;

class Cityarea extends Controller
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function getAreas(Request $request)
    {
        $level = (int)$request->get('level', 1);
        $parentId = (int)$request->get('parent_id', 0);
        if ($level < 1 || $level > 3) $level = 1;

        $log = date('c') . ' ' . $request->url(true) . ' ' . json_encode($request->get()) . PHP_EOL;
        file_put_contents($_SERVER["DOCUMENT_ROOT"]."/../runtime/ysapi_cityarea_getAreas.log", $log, FILE_APPEND);

        $prefix = config('database.prefix');
        $columns = [];
        try {
            $columns = Db::query("SHOW COLUMNS FROM `{$prefix}cityarea`");
        } catch (\Exception $e) {
            $columns = [];
        }
        $fields = [];
        foreach ($columns as $col) { if (isset($col['Field'])) $fields[] = $col['Field']; }
        $parentCandidates = ['pid','parent_id','parent','city_id','upid'];
        $parentField = null;
        foreach ($parentCandidates as $cand) { if (in_array($cand, $fields)) { $parentField = $cand; break; } }

        $query = Db::name('cityarea')->where('status', 1);
        if ($parentField) {
            if ($level === 1) {
                $query = $query->where($parentField, 0);
            } else {
                $query = $query->where($parentField, $parentId);
            }
        }

        if ($parentField) {
            $query = $query->field("id,name,{$parentField} as pid");
        } else {
            $query = $query->field('id,name');
        }

        $list = $query->order('weigh desc, id asc')->select();

        return json([
            'code' => 200,
            'msg' => 'ok',
            'data' => $list
        ]);
    }
}